package com.three.servie.implement;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.three.servie.GPT3Service;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.springframework.stereotype.Service;

@Service
public class GPT3ServiceImpl implements GPT3Service {
    @Override
    public String getMessageFromGPT(String question) {
        OkHttpClient client = new OkHttpClient
                .Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
        MediaType mediaType = MediaType.parse("application/json");

        // 设置请求体
        String jsonBody = "{"
                + "\"model\": \"qianxiao\","
                + "\"messages\": [{\"role\": \"user\", \"content\": \"" + question + " \"}]"
                + "}";
        RequestBody requestBody = RequestBody.create(mediaType, jsonBody);

        // 创建请求
        Request request = new Request.Builder()
                .url("http://10.224.12.4:9000/v1/chat/completions")
                .addHeader("Authorization", "none")
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected response code: " + response);
            }

            String responseBody = response.body().string();

            // 使用Gson解析JSON
            Gson gson = new Gson();
            JsonObject json = gson.fromJson(responseBody, JsonObject.class);

            // 获取content
            String content = json.get("choices").getAsJsonArray().get(0).getAsJsonObject().get("message").getAsJsonObject().get("content").getAsString();
            System.out.println(content);
            return content;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
